package com.zzh.controller;

import com.alibaba.fastjson.JSON;
import com.zjiecode.wxpusher.client.WxPusher;
import com.zjiecode.wxpusher.client.bean.Message;
import com.zjiecode.wxpusher.client.bean.MessageResult;
import com.zjiecode.wxpusher.client.bean.Result;
import com.zzh.bean.JsonRootBean;
import com.zzh.bean.Shop;
import com.zzh.bean.ShopInfo;
import com.zzh.service.ShopService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;

/**
 * @author zzh
 * @description: TODO
 * @date 2023年05月09日 16:20
 */
@Slf4j
@RestController
@RequestMapping("/test")
public class ShopController {
    private static String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NiJ9.eyJleHAiOjE2ODQ5MTc3MDIsInVzZXJJZCI6NTI4Mjc3MzU4OTkzMDA3NSwiaWF0IjoxNjgzNzA4MTAyfQ.afwcxvsrLNbyH3WewboRLgd3fOnyP_DF4X3ZcGQqcsHFm1xzDtQyC4KBW3xRHrqeRm6wItxBh0hYS3KQIuthzw";
    //private static int[] arr = {282,283,361,608,365,364,363,397,395};


    @Resource
    private JavaMailSender javaMailSender;

    @Autowired
    private ShopService shopService;

    @Value("${spring.mail.username}")
    private String mailFrom;

    //@GetMapping("/post")
    public JsonRootBean sendJsonPost() {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        String jsonData = "{\"page\":1,\"size\":20,\"resourceId\":5,\"orderBy\":\"SORT_DESC\"}";
        //5 / 6 / 7
        try {
            HttpClient client = new HttpClient(); // 客户端实例化
            PostMethod postMethod = new PostMethod("https://mall-api.xwindlab.com/goods/queryGoodsListByDisplayResource"); // 请求方法post，可以将请求路径传入构造参数中

            postMethod.addRequestHeader("Content-type", "application/json; charset=utf-8");
            postMethod.addRequestHeader("Authorization", token);
            byte[] requestBytes = jsonData.getBytes("utf-8"); // 将参数转为二进制流

            InputStream inputStream = new ByteArrayInputStream(requestBytes, 0, requestBytes.length);
            // 请求体
            RequestEntity requestEntity = new InputStreamRequestEntity(inputStream, requestBytes.length, "application/json; charset=utf-8");
            postMethod.setRequestEntity(requestEntity); // 将参数放入请求体
            int i = client.executeMethod(postMethod); // 执行方法
            System.out.println("请求状态" + i);

            // 这里因该有判断的，根据请求状态判断请求是否成功，然后根据第三方接口返回的数据格式，解析出我们需要的数据
            byte[] responseBody = postMethod.getResponseBody(); // 得到相应数据
            String s = new String(responseBody);
            System.out.println(s);
            result = s;
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！" + e);
            e.printStackTrace();
        }

        // 使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

        JsonRootBean bean = JSON.parseObject(result, JsonRootBean.class);
        Shop data = bean.getData();
        List<ShopInfo> list = data.getList();
        for (ShopInfo shopInfo : list) {
            Boolean hasInv = shopInfo.getHasInv();
            String value = shopInfo.getSloganMap().get("1");
            if (value.contains("1:1") || value.contains("2:1")) {
                System.out.println(shopInfo.getName() + ":  " + shopInfo.getId() + "  :" + value + ":" + shopInfo.getHasInv());
                if (shopInfo.getHasInv() || shopInfo.getId() == 282) {
                    Message message = new Message();
                    message.setAppToken("AT_X2qDwjcIYzrrsUwi4y4KpP8bSQlZFtK8");
                    message.setContentType(Message.CONTENT_TYPE_TEXT);
                    message.setContent(shopInfo.getName());
                    message.setTopicId(System.currentTimeMillis());
                    message.setUid("UID_m5uD0uGFMU23QfkIerfk3Tmt1Rk7");
                    message.setUrl("http://wxpuser.zjiecode.com");
                    Result<List<MessageResult>> results = WxPusher.send(message);
                    System.out.println("测试法");
                }
            }
        }
        //list.stream().filter(shopInfo -> shopInfo.get)
        return bean;
    }


    @GetMapping("/sendEmail")
    public void sendEmail() {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        try {
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
            mimeMessageHelper.setFrom(new InternetAddress(mailFrom, "你的专属点餐员", "UTF-8")); //设置发件人
            String[] mailTo = new String[]{"1287089542@qq.com"};
            mimeMessageHelper.setTo(mailTo); //设置收件人
            mimeMessageHelper.setSubject("集市上新"); //设置邮件标题
            mimeMessageHelper.setText("测试邮件发送！", true); //设置邮件内容
            //mimeMessageHelper.setCc(); //设置抄送人
            long start = System.currentTimeMillis();
            log.info("邮件开始发送~~~");
            javaMailSender.send(mimeMessage);
            long end = System.currentTimeMillis();
            long time = (end - start) / 1000;
            log.info("邮件发送成功，耗时:{}秒", time);
        } catch (MessagingException | UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    @GetMapping("/addUid")
    public Boolean sendSms(String uid) {
        return CaCheUidUtils.addUid(uid);
    }
}
